// request.js
class Request {
  constructor(baseUrl = '/repair-manager', tokenKey = 'Cer-Sign') {
    this.baseUrl = baseUrl;
    this.tokenKey = tokenKey;
  }

  // 获取本地存储的认证token
  getToken() {
    return uni.getStorageSync('token');
  }

  // 设置认证token
  setToken(token) {
	//  console.log("setToken:"+token)
    uni.setStorageSync('token', token);
	//  console.log("getToken:"+uni.getStorageSync('token'))
  }

  // 构建请求配置
  buildConfig(config = {}) {
	//  console.log(this.getToken)
    const token = this.getToken();
	//console.log("请求token:"+token);
    const defaultConfig = {
      baseUrl: this.baseUrl,
      header: {
        [this.tokenKey]: token || '',
        'Content-Type': 'application/json',
		 'Terminal-Type': 'mobile'
      },
      method: 'GET',
      dataType: 'json',
      responseType: 'text'
    };

    return { ...defaultConfig, ...config };
  }

  // 发送请求
  request(config) {
    const reqConfig = this.buildConfig(config);
    return new Promise((resolve, reject) => {
      uni.request({
        ...reqConfig,
        url: reqConfig.baseUrl + reqConfig.url,
        success: (res) => {
          if (res.statusCode >= 200 && res.statusCode < 300) {
			  if(res.data.code === '000'){
				  resolve(res.data);  
			  }else if(res.data.code === '002'){
				  uni.clearStorageSync();
				  uni.navigateTo({
				  	url: '/pages/login/index',
				  });
			  }else{
				uni.showToast({
					title:res.data.message ,
					icon:'none',
					duration:5000
				})
			  }
          
          } else {
            reject({
              statusCode: res.statusCode,
              errMsg: res.data.message || '请求失败'
            });
          }
        },
        fail: (err) => {
          reject({
            statusCode: -1,
            errMsg: err.errMsg || '网络错误'
          });
        }
      });
    });
  }

  // 快捷方法：GET请求
  get(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      data,
      method: 'GET'
    });
  }

  // 快捷方法：POST请求
  post(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      data,
      method: 'POST'
    });
  }

  // 快捷方法：PUT请求
  put(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      data,
      method: 'PUT'
    });
  }

  // 快捷方法：DELETE请求
  delete(url, data = {}, config = {}) {
    return this.request({
      ...config,
      url,
      data,
      method: 'DELETE'
    });
  }
}    

export default new Request();